<?php

namespace App\Console\Commands\ES;

use App\Models\Info;
use Elasticsearch\ClientBuilder;

class InfoMapping extends ESBaseCommand
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'mapping:info';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'build/rebuild info mapping';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->index = 'info_index2';
        $this->model = Info::class;
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        // get config
        $host = $this->host;
        $index = $this->index;
        $client = ClientBuilder::create()->setHosts($host)->build();

        // make sure index not exists
        if ($client->indices()->exists(['index' => $index])) {
            $this->warn("Index {$index} exists, deleting...");
            $client->indices()->delete(['index' => $index]);
        }
        $this->info("Creating index: {$index}");

        // built or rebuilt index
        try {
            $result = $client->indices()->create([
                'index' => $index,
                'body' => [
                    'settings' => [
                        'number_of_shards' => 1,
                        'number_of_replicas' => 1,
                    ],
                    'mappings' => [
                        'properties' => [
                            'id' => [
                                'type' => 'long',
                            ],
                            'key' => [
                                'type' => 'text',
                                'fields' => [
                                    'keyword' => [
                                        'type' => 'keyword',
                                        'ignore_above' => 256,
                                    ],
                                ],
                            ],
                        ],
                    ],
                ]
            ]);
        } catch (\Exception $e) {
            $this->warn("[ERROR] ".$e->getCode().' - '.$e->getMessage());
            return false;
        }
        $this->info("Create index: {$index} successful.");

        // import data
        $this->import();
        $this->info("Import data for index: {$index} successful.");

        return 0;
    }

}
